<template>
  <view class="container">
    <view class="checkStatus" v-if="isShowCheckStatus">审核状态：
      <text>{{checkStatus}}</text>
    </view>
    <view class="item">
      <view class="username-cardnumber">
        <text>姓名</text>
        <view class="item-right">
          <input class="input" type="text" placeholder="请输入姓名" v-model="form.username">
        </view>
      </view>
      <view class="username-cardnumber">
        <text>身份证号码</text>
        <view class="item-right">
          <input class="input" type="text" placeholder="请输入身份证号码" v-model="form.identityCard">
        </view>
      </view>
    </view>
    <view class="item">
      <text class="tip">请上传身份证正反面</text>
      <view class=" id-card-upload">
        <view class="image" v-if="form.idcardFrontUrl">
          <view class="image-remove" @click="removePicture(1)">x</view>
          <image :src="baseUrl + form.idcardFrontUrl" mode=""></image>
        </view>
        <image class="image" @click="onChooseImage(1)" v-else src="/static/images/Group48097815.png" mode=""></image>
        <view class="image" v-if="form.idcardBackUrl">
          <view class="image-remove" @click="removePicture(2)">x</view>
          <image :src="baseUrl + form.idcardBackUrl" mode=""></image>
        </view>
        <image class="image" @click="onChooseImage(2)" v-else src="/static/images/Group48097817.png" mode=""></image>
      </view>
    </view>
    <view class="user-agreement">
      <label @click="isAgreeMent" class="label">
        <checkbox :checked="agree" />同意
      </label>
      <view>
        <text @click="onClickUserProtocol" style="color: #1eadef;">《用户协议》</text>和<text @click="onClickPrivacyPolicy"
          style="color: #1eadef;">《隐私政策》</text>
      </view>
    </view>
    <view class="footer-button" v-if="showSubmitButton">
      <FooterBottom title="提交审核" @onclick="submit"></FooterBottom>
    </view>

  </view>
</template>

<script>
  export default {
    data() {
      return {
        form: {
          // username: '成功',
          // identityCard: '412727199912226666',
          username: '',
          identityCard: '',
          idcardFrontUrl: '',
          idcardBackUrl: ''
        },
        baseUrl: uni.gRequest.file,
        showSubmitButton: true,
        checkStatus: '',
        isShowCheckStatus: false,
        id: '', //用户实名认证返回的id,
        agree: false,
        userProtocol: '',
        privacyPolicy: ''
      };
    },
    onLoad() {
      this.getUserAuthInfo()
      this.getUserAgree()
    },
    methods: {
      onClickUserProtocol() {
        uni.showModal({
          title: '用户协议',
          content: this.userProtocol,
        })
      },
      onClickPrivacyPolicy() {
        uni.showModal({
          title: '隐私政策',
          content: this.privacyPolicy,
        })
      },
      async getUserAgree() {
        const res = await uni.gRequest.get('/app/config/configKey/security.policy')
        this.privacyPolicy = res?.msg || ''
        const res1 = await uni.gRequest.get('/app/config/configKey/user.agreement')
        this.userProtocol = res1?.msg || ''
      },
      isAgreeMent() {
        this.agree = !this.agree
      },
      // 获取用户实名认证信息
      async getUserAuthInfo() {
        const res = await uni.gRequest.get('/app/auth/info')
        if (res.data && res.data.status != 3) {
          this.showSubmitButton = false
          uni.showToast({
            icon: 'none',
            title: '认证信息已提交请勿重新上传'
          })
        }
        if (res.data && res.data.id) {
          this.id = res.data.id
          this.isShowCheckStatus = true
          if (res.data.status == 1) {
            this.checkStatus = '待审核'
          } else if (res.data.status == 2) {
            this.checkStatus = '审核通过'
          } else if (res.data.status == 3) {
            this.checkStatus = '审核不通过'
          }
          this.form.username = res.data.userName
          this.form.identityCard = res.data.identifyNumber
          this.form.idcardFrontUrl = res.data.frontImage
          this.form.idcardBackUrl = res.data.backImage
        }
      },
      // 清除图片
      removePicture(i) {
        i == 1 ? (this.form.idcardFrontUrl = '') : (this.form.idcardBackUrl = '')
      },
      // 选择图片
      async onChooseImage(i) {
        const res = await uni.chooseMedia({
          count: 1,
          mediaType: 'image',
        })
        if (i == 1) {
          this.form.idcardFrontUrl = res.tempFiles[0].tempFilePath
          this.uploadCard(this.form.idcardFrontUrl)
        } else {
          this.form.idcardBackUrl = res.tempFiles[0].tempFilePath
          this.uploadCard(this.form.idcardBackUrl)
        }
      },
      // 上传到服务器
      uploadCard(idcardUrl) {
        // 调用 API 上传图片
        var userInfo = uni.getStorageSync('userInfo');
        wx.uploadFile({
          url: this.baseUrl + '/common/upload',
          filePath: idcardUrl,
          name: 'file',
          header: {
            Authorization: 'Bearer ' + userInfo.token,
          },
          success: (result) => {
            // 处理返回的 json 数据
            const data = JSON.parse(result.data)
            if (data.code !== 200) {
              return wx.showToast({
                icon: 'none',
                title: '上传图片失败!'
              })
            }
            // 渲染数据
            // TODO 将form的临时图片地址换成线上地址
            idcardUrl == this.form.idcardFrontUrl ? this.form.idcardFrontUrl = data.fileName : this.form
              .idcardBackUrl = data.fileName

          },
        })
      },
      // 姓名验证
      usernameVerify() {
        return /^(?:[\u4e00-\u9fa5·]{2,16})$/.test(this.form.username)
      },
      // 身份证验证
      idCardVerify() {
        return /^[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|10|11|12)(?:0[1-9]|[1-2]\d|30|31)\d{3}[\dXx]$/.test(this.form
          .identityCard)
      },
      // 表单提交
      submit() {
        if (!this.usernameVerify()) return uni.showToast({
          icon: 'none',
          title: '请输入有效姓名'
        })
        if (!this.idCardVerify()) return uni.showToast({
          icon: 'none',
          title: '请输入有效身份证'
        })
        if (!this.form.idcardFrontUrl || !this.form.idcardBackUrl) return uni.showToast({
          icon: 'none',
          title: '请上传有效身份证件照'
        })
        if (!this.agree) {
          return uni.showToast({
            icon: 'none',
            title: '请点击同意用户协议'
          })
        }
        // this.uploadCard(this.form.idcardFrontUrl)
        // this.uploadCard(this.form.idcardBackUrl)
        // 数据上传
        this.addUserRealAuth()
      },
      // 添加认证信息的接口
      async addUserRealAuth() {
        const res = await uni.gRequest.post('/app/auth/add', {
          userName: this.form.username,
          identifyNumber: this.form.identityCard,
          frontImage: this.form.idcardFrontUrl,
          backImage: this.form.idcardBackUrl,
          id: this.id,
          status: '1'
        })
        if (res.msg == '操作成功') {
          uni.showToast({
            icon: 'none',
            title: '提交成功，请等待审核',
          })
          setTimeout(() => {
            uni.switchTab({
              url: "/pages/switchPages/user"
            })
          }, 1000)
        }

      },

    }
  }
</script>

<style lang="scss">
  .user-agreement {
    display: flex;
    align-items: center;
    margin-top: 30rpx;
    padding: 20rpx 30rpx;
  }

  .label {
    margin-right: 20rpx;
    display: flex;
    align-items: center;
  }

  .container {
    border-top: 1rpx #eee solid;
  }

  .checkStatus {
    border-radius: 20rpx;
    padding: 4rpx 15rpx;
    background-color: #4caa12;
    display: inline-block;
    font-size: 22rpx;
    margin: 26rpx 20rpx 0;
  }

  .item {
    background: #FFFFFF;
    box-shadow: 0rpx 1rpx 20rpx 0rpx rgba(182, 182, 182, 0.15);
    border-radius: 10rpx 10rpx 10rpx 10rpx;
    margin: 30rpx 30rpx 0;
    padding: 0 30rpx;

    .tip {
      line-height: 100rpx;
      font-weight: 500;
      font-size: 30rpx;
      color: #333333;
    }
  }

  .username-cardnumber {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1rpx #eee solid;
    font-size: 28rpx;
    color: #000000;
    padding: 30rpx 0;

    &:last-child {
      border-bottom: none;
    }

    .item-right {
      flex: 1;

      .input {
        text-align: right;
        padding: 0 20rpx 0 30rpx;
      }
    }
  }

  .id-card-upload {
    display: flex;
    justify-content: space-between;
    padding-bottom: 40rpx;

    image {
      width: 298rpx;
      height: 325rpx;
    }

    .image {
      width: 298rpx;
      height: 325rpx;
      position: relative;

      .image-remove {
        width: 50rpx;
        height: 50rpx;
        text-align: center;
        line-height: 40rpx;
        position: absolute;
        right: 0;
        top: 0;
        color: #fff;
        border-radius: 0 20rpx 0 20rpx;
        background-color: rgba($color: #000000, $alpha: .6);

      }

    }
  }

  .footer-button {
    margin-top: 180rpx;
  }
</style>
